<template>
  <div style="padding: 20px">
    <el-container>
      <el-header>
        <el-descriptions class="margin-top" :title="title" :column="3" border>
          <el-descriptions-item label="描述" width="60px">
            {{ description }}
          </el-descriptions-item>
        </el-descriptions>
      </el-header>
      <el-main>
        <render
          :draw-item-list="renderJson"
          :tempId="id"
          v-model="formModel"
        ></render>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import Render from './Render.vue'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getFormTempInfo } from '@/request/formTemp'
import { formConfigInfo, formConfigUpsert } from '@/request/formConfig'
import { ElMessage } from 'element-plus'

const router = reactive(useRouter())
let id = router.currentRoute.params.id
const requestJson = ref([])
const renderJson = ref(requestJson)
const itemDict = ref({})
// 必须var 确保全局
var formModel = ref([])

const title = ref('')
const description = ref('')

onMounted(async () => {
  await initFormTemp()
  await initFormConfig()
})

const initFormTemp = async function () {
  let response = await getFormTempInfo({ id: id })
  let { code, data, msg } = response
  if (code === 200) {
    let { name, info, content } = data
    let itemList = JSON.parse(content, null)

    title.value = name
    description.value = info
    requestJson.value = itemList

    for (const item of itemList) {
      itemDict.value[item['__config__']['itemName']] = {
        label: item['__config__']['label']
      }
    }
  } else {
    ElMessage({
      type: 'error',
      message: msg
    })
    title.value = ''
    description.value = '表单已被禁用'
    requestJson.value = []
  }
}

const initFormConfig = async function () {
  let userId = localStorage.getItem('userId')
  let response = await formConfigInfo({ id: id, userId: userId })
  let { code, data, msg } = response
  if (code === 200) {
    for (let key in data) {
      let value = convertToNumber(data[key])
      formModel.value[key] = value
      itemDict.value[key]['value'] = value
    }
  } else {
    ElMessage({
      type: 'error',
      message: msg
    })
  }
}

watch(
  formModel,
  (val) => {
    console.info(val)
  },
  { deep: true }
)

const submit = function () {
  let fieldList = []
  let formItem = reactive(formModel.value)
  for (let item in formItem) {
    fieldList.push({
      name: item,
      value: formItem[item]
    })
  }
  let userId = localStorage.getItem('userId')
  formConfigUpsert({
    formId: id,
    fields: fieldList,
    userId: userId
  })
    .then((resp) => {
      let { code, msg } = resp
      if (code === 200) {
        ElMessage({
          type: 'success',
          message: msg
        })
      } else {
        ElMessage({
          type: 'error',
          message: msg
        })
      }
    })
    .catch((reason) => {
      ElMessage({
        type: 'error',
        message: reason
      })
    })
}

function convertToObject(target) {
  try {
    return eval(target)
  } catch (e) {
    return target
  }
}
function convertToNumber(str) {
  if (typeof str === 'string') {
    const num = parseFloat(str)
    if (!isNaN(num)) {
      if (num.toString() === str) {
        return num
      }
      return str
    }
  }
  return str
}
</script>

<style scoped>
.el-descriptions {
  text-align: center;
}
</style>
